package sany.iec.service.impl;

import com.serotonin.modbus4j.ModbusSlaveSet;
import com.serotonin.modbus4j.ip.tcp.TcpSlave;
import org.openmuc.j60870.Server;
import org.springframework.stereotype.Service;
import sany.iec.entity.ServerEntity;
import sany.iec.enums.EnableEnum;
import sany.iec.enums.ServerType;
import sany.iec.service.IEC104ServerService;
import sany.iec.service.ModbusServerService;
import sany.iec.service.ServerService;

import javax.annotation.Resource;
import java.io.IOException;

/**
 * @Author 托马斯
 * @Date 2025/7/6 18:09
 * @Description ServerServiceImpl
 */
@Service
public class ServerServiceImpl implements ServerService {

    @Resource
    private IEC104ServerService iec104Service;

    @Resource
    private ModbusServerService modbusService;

    @Override
    public void startServer(ServerEntity server) throws IOException {
        if (server.getServerType().equals(ServerType.IEC104)) {
            if (server.getIEC104Server() == null && server.getEnable().equals(EnableEnum.Enabled)) {
                Server build = Server.builder().setPort(server.getPort()).build();
                server.setIEC104Server(build);
                iec104Service.startServer(server, build);
            }
        } else {
            if (server.getModbusServerSet() == null && server.getEnable().equals(EnableEnum.Enabled)) {
                ModbusSlaveSet tcpSlave = new TcpSlave(server.getPort(), false);
                server.setModbusServerSet(tcpSlave);
                modbusService.startServer(server, tcpSlave);
            }
        }
    }

    @Override
    public void stopServer(ServerEntity server) {
        if (server.getServerType().equals(ServerType.IEC104)) {
            server.getIEC104Server().stop();
            iec104Service.removeServer(server.getIEC104Server());
            server.setIEC104Server(null);
        } else {
            server.getModbusServerSet().stop();
            server.setModbusServerSet(null);
        }
    }
}
